using System;
using System.ComponentModel;
using System.Windows.Forms;
using VideoSource;
using Tiger.Video.VFW;
using System.IO.Ports;

namespace motion
{
    /// <summary>
    /// Summary description for MainForm
    /// </summary>
    public class MainForm : System.Windows.Forms.Form
    {
        
        private const int statLength = 15;
        private int statIndex = 0, statReady = 0;
        private int[] statCount = new int[statLength];
        private IMotionDetector detector = null;
        private int intervalsToSave = 0;
        private AVIWriter writer = null;
        private bool saveOnMotion = false;
        private System.Windows.Forms.MainMenu mainMenu;
        private System.Timers.Timer timer;
        private System.Windows.Forms.StatusBar statusBar;
        private System.Windows.Forms.StatusBarPanel fpsPanel;
        private System.Windows.Forms.Panel panel;
        private motion.CameraWindow cameraWindow;
        private IContainer components;
        private string url;

        public MainForm( )
        {
            InitializeComponent();
            String cumbres = "http://camaracumbres.dyndns.org:8081/videostream.cgi?user=saury&pwd=opencam";
            String libertador = "http://camaralibertador.dyndns.org:8081/videostream.cgi?user=saury&pwd=opencam";
            url = libertador;
            MJPEGStream mjpegSource = new MJPEGStream();
            mjpegSource.VideoSource = url;

            OpenVideoSource(mjpegSource);
            //proesamiento del video
            SetMotionDetector();
        }
        protected override void Dispose( bool disposing )
        {
            if ( disposing )
            {
                if ( components != null )
                {
                    components.Dispose( );
                }
            }
           base.Dispose( disposing );
        }
        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent( )
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
            this.mainMenu = new System.Windows.Forms.MainMenu(this.components);
            this.timer = new System.Timers.Timer();
            this.statusBar = new System.Windows.Forms.StatusBar();
            this.fpsPanel = new System.Windows.Forms.StatusBarPanel();
            this.panel = new System.Windows.Forms.Panel();
            this.cameraWindow = new motion.CameraWindow();
           // ((System.ComponentModel.ISupportInitialize)(this.timer)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.fpsPanel)).BeginInit();
            this.panel.SuspendLayout();
            this.SuspendLayout();        
            // fpsPanel
            this.fpsPanel.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring;
            this.fpsPanel.Name = "fpsPanel";
            this.fpsPanel.Width = 310;
            // panel
            this.panel.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.panel.Controls.Add(this.cameraWindow);
            this.panel.Dock = System.Windows.Forms.DockStyle.Fill;
            this.panel.Location = new System.Drawing.Point(0, 0);
            this.panel.Name = "panel";
            this.panel.Size = new System.Drawing.Size(327, 249);
            this.panel.TabIndex = 2;
            this.panel.Paint += new System.Windows.Forms.PaintEventHandler(this.PanelPaint);
            // cameraWindow
            this.cameraWindow.BackColor = System.Drawing.SystemColors.AppWorkspace;
            this.cameraWindow.Camera = null;
            this.cameraWindow.Location = new System.Drawing.Point(3, 3);
            this.cameraWindow.Name = "cameraWindow";
            this.cameraWindow.Size = new System.Drawing.Size(320, 240);
            this.cameraWindow.TabIndex = 1;
            this.cameraWindow.Click += new System.EventHandler(this.CameraWindowClick);
            // MainForm

            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(327, 271);
            this.Controls.Add(this.panel);
            this.Controls.Add(this.statusBar);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Menu = this.mainMenu;
            this.Name = "MainForm";
            this.Text = "Motion Detector";
            this.Load += new System.EventHandler(this.MainFormLoad);
            this.Closing += new System.ComponentModel.CancelEventHandler(this.MainFormClosing);
            ((System.ComponentModel.ISupportInitialize)(this.timer)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.fpsPanel)).EndInit();
            this.panel.ResumeLayout(false);
            this.ResumeLayout(false);

        }
        #endregion
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main( )
        {
            Application.Run( new MainForm( ) );
        }
        // On form closing
        private void MainFormClosing( object sender, System.ComponentModel.CancelEventArgs e )
        {
            CloseFile( );
        }
        // Close the main form
        private void ExitFileItemClick( object sender, System.EventArgs e )
        {
            this.Close( );
        }      
        // Open video source
        private void OpenVideoSource( IVideoSource source )
        {
            // set busy cursor
            this.Cursor = Cursors.WaitCursor;

            // close previous file
            CloseFile( );

            // create camera
            Camera camera = new Camera( source, detector );
            // start camera
            camera.Start( );

            // attach camera to camera window
            cameraWindow.Camera = camera;

            // reset statistics
            statIndex = statReady = 0;

            // set event handlers
            camera.NewFrame += new EventHandler( CameraNewFrame );
            

            // start timer
            timer.Start( );

            this.Cursor = Cursors.Default;
        }
        // Close current file
        private void CloseFile( )
        {
            Camera camera = cameraWindow.Camera;

            if ( camera != null )
            {
                // detach camera from camera window
                cameraWindow.Camera = null;

                // signal camera to stop
                camera.SignalToStop( );
                // wait for the camera
                camera.WaitForStop( );

                camera = null;

                if ( detector != null )
                    detector.Reset( );
            }

            if ( writer != null )
            {
                writer.Dispose( );
                writer = null;
            }
            intervalsToSave = 0;
        }
        // On timer event - gather statistic
        private void TimerElapsed( object sender, System.Timers.ElapsedEventArgs e )
        {
            Camera camera = cameraWindow.Camera;

            if ( camera != null )
            {
                // get number of frames for the last second
                statCount[statIndex] = camera.FramesReceived;

                // increment indexes
                if ( ++statIndex >= statLength )
                    statIndex = 0;
                if ( statReady < statLength )
                    statReady++;

                float fps = 0;

                // calculate average value
                for ( int i = 0; i < statReady; i++ )
                {
                    fps += statCount[i];
                }
                fps /= statReady;

                statCount[statIndex] = 0;

                fpsPanel.Text = fps.ToString( "F2" ) + " fps";
            }

            // descrease save counter
            if ( intervalsToSave > 0 )
            {
                if ( ( --intervalsToSave == 0 ) && ( writer != null ) )
                {
                    writer.Dispose( );
                    writer = null;
                }
            }
        }
        private void SetMotionDetector( )
        {
            Camera camera = cameraWindow.Camera;
            // set motion detector to camera
            if ( camera != null )
            {
                camera.Lock( );
                camera.MotionDetector = detector;
                // reset statistics
                statIndex = statReady = 0;
                camera.Unlock( );
            }
        }
        // On new frame
        private void CameraNewFrame( object sender, System.EventArgs e )
        {
            if ( ( intervalsToSave != 0 ) && ( saveOnMotion == true ) )
            {
                // lets save the frame
                if ( writer == null )
                {
                    // create file name
                    DateTime date = DateTime.Now;
                    String fileName = String.Format( "{0}-{1}-{2} {3}-{4}-{5}.avi",
                        date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second );
                    try
                    {
                        // create AVI writer
                        writer = new AVIWriter( "wmv3" );
                        // open AVI file
                        writer.Open( fileName, cameraWindow.Camera.Width, cameraWindow.Camera.Height );
                    }
                    catch ( ApplicationException ex )
                    {
                        if ( writer != null )
                        {
                            writer.Dispose( );
                            writer = null;
                        }
                    }
                }

                // save the frame
                Camera camera = cameraWindow.Camera;

                camera.Lock( );
                writer.AddFrame( camera.LastFrame );
                camera.Unlock( );
            }
        }
        private void MainFormLoad(object sender, EventArgs e)
        {
            Timer MyTimer = new Timer();
            MyTimer.Interval = (1 * 60 * 1000); // al min se dispara el evento de abajo
            MyTimer.Tick += new EventHandler(MyTimerTick);
            MyTimer.Start();

        }
        //envio de SMS
        private void MyTimerTick(object sender, EventArgs e)
        {

            try
            {
                clsSMS Sms = new clsSMS();
                SerialPort s1 = Sms.OpenPort("COM4", 9600, 8, 1, 300);

                Sms.sendMsg(s1, "+584242276615", "Pruebita");
                Sms.ClosePort(s1);
            }
            catch (Exception ex) { }
            
            //MessageBox.Show("ya se calculo la velocidad jejeje.", " el Tiempo paso papa");
            this.Close();
        }
        private void CameraWindowClick(object sender, EventArgs e)
        {
                // create video source
                VideoFileSource fileSource = new VideoFileSource();
                OpenVideoSource(fileSource);
        }
        private void PanelPaint(object sender, PaintEventArgs e)
        {
        }
        private void OpenFileItemClick(object sender, EventArgs e)
        {
        }  
    }
}
